/// <reference path="../../global.d.ts" />

import { MessageTypeEnum } from '@enum/message-type.enum';
import { applyCallBack } from '@utils/applyCallBack';
import { copyToText } from '@utils/copyToClipboard';
import { createEditorDialog, type MonacoEditor } from '@utils/createEditorDialog';
import { getDatesInRange, getTodayDate, getSpecialDayBeforeDate } from '@utils/getDate';
import { showMessage } from '@utils/showMessage';
import { getCollectedBugs } from '@utils/bugCollection';
import { bugHistoryModal } from '@components/bugHistory.vue';
import { BugReportListItem, getReportBugsByDate } from '@utils/getReportBugs';
import { migrateReport } from '@utils/migrateReport';
import { bugCollectionModal } from '@components/bugCollection.vue';

const showTopButtons = !window.location.pathname.includes("attachment.cgi") && !window.location.pathname.includes("show_activity.cgi");

export default () => {
  const navigationABtn = document.querySelectorAll('#bugzilla-body .navigation a');
  const navigationFontBtn = document.querySelectorAll('#bugzilla-body .navigation i font');
  const links = document.querySelectorAll('.links a');
  const linksUL = document.querySelector('.links');
  const quicksearchTopInput = document.querySelector('#quicksearch_top') as HTMLInputElement;
  const quicksearchBottomInput = document.querySelector('#quicksearch_bottom') as HTMLInputElement;
  const findTopBtn = document.querySelector('#find_top') as HTMLInputElement;
  const findBottomBtn = document.querySelector('#find_bottom') as HTMLInputElement;
  const separators = document.querySelectorAll('.links .separator');
  const searchBtns = document.querySelectorAll('input[value="Search"]');

  // 清除 14 天之前的 bugs
  const clearDays = getDatesInRange(getSpecialDayBeforeDate(new Date(), 14), 30);

  for (let i = 0; i < clearDays.length; i++) {
    const date = clearDays[i];
    const yesterdayReportLocal = localStorage.getItem(date) ?? null;
    if (yesterdayReportLocal) {
      localStorage.removeItem(date);
    }
  }

  // 日报的数据结构变化了，这里做下数据迁移
  migrateReport();

  const navBtnAddStyle = (node: HTMLElement, isDisabled = false) => {
    node.classList.add('custom-button');
    node.classList.add('plain-button');
    isDisabled && node.classList.add('disabled-button');
    // @ts-ignore
    node.style = "margin-left: 2px; padding-top: 5px !important";

    if (node.innerText === 'First') {
      node.innerText = '第一个';
    }
    if (node.innerText === 'Last') {
      node.innerText = '最后一个';
    }
    if (node.innerText === 'Prev') {
      node.innerText = '上一个';
    }
    if (node.innerText === 'Next') {
      node.innerText = '下一个';
    }
    if (node.innerText === 'Show last search results') {
      node.innerText = '显示上一次的搜索结果';
    }
    if (node.innerText === 'This bug is not in your last search results.') {
      node.innerText = '这个 bug 不是你上一次搜索的结果';
    }
  }

  navigationABtn.forEach((node: any) => {
    navBtnAddStyle(node);
  })
  navigationFontBtn.forEach((node: any) => {
    navBtnAddStyle(node, true);
  })

  const searchBtnHandler = (btn: HTMLInputElement, input: HTMLInputElement) => {
    btn.value = '查询/刷新';

    btn.addEventListener('click', (e) => {
      e.preventDefault();

      if (input.value) {
        const isBugId = /^\d+$/.test(input.value);

        if(isBugId) {
          window.open(`http://192.168.1.31/bugzilla/show_bug.cgi?id=${input.value}`, '_blank');
        } else {
          window.open(`http://192.168.1.31/bugzilla/buglist.cgi?quicksearch=${input.value}`, '_blank');
        }
        input.value = "";
      } else {
        window.location.reload();
      }
    })
  }

  if (findTopBtn && quicksearchTopInput) {
    searchBtnHandler(findTopBtn, quicksearchTopInput);
  }

  if (findBottomBtn && quicksearchBottomInput) {
    searchBtnHandler(findBottomBtn, quicksearchBottomInput);
  }

  if (links) {
    Array.from(links).forEach((link) => {
      link.classList.add('link-title');
    })
  }
  if (separators) {
    Array.from(separators).forEach((separator: any) => {
      separator.innerText = '|';
      separator.classList.add('separators');
    })
  }
  if (searchBtns) {
    Array.from(searchBtns).forEach((submitBtn) => {
      submitBtn.classList.add('custom-button');
      submitBtn.classList.add('plain-button');
    })
  }

  const createTopBtn = (text = '', clickFn: (btn: HTMLSpanElement) => void, beforeCreate?: (btn: HTMLSpanElement) => void) => {
    const li = document.createElement('li');
    const btn = document.createElement('span');
    btn.innerText = text;
    btn.classList.add('custom-button');
    applyCallBack(beforeCreate, btn);

    btn.addEventListener('click', () => clickFn(btn));
    li.appendChild(btn);
    linksUL!.appendChild(li);
  }

  if (linksUL && showTopButtons) {
    createTopBtn('生成日报', async () => {
      const todayDate = getTodayDate();
      const todayReportLocal = getReportBugsByDate(todayDate);

      let editor: MonacoEditor = null;
      const { monaco, editorNode } = await createEditorDialog({
        cancelText: '关闭',
        okText: '复制并去填写',
        bodyStyle: 'width: 1200px; height: 80vh',
        onOk: (closeDialog) => {
          const value = editor!.getValue();

          if (value) {
            copyToText(value);
            closeDialog();
            setTimeout(() => {
              window.open('https://doc.weixin.qq.com/forms/j/AHEA-wd3ABEAKYAkAa2AEsNj3jF67sQBj_fork?journaluuid=6Guqz1wm4f1cXAq8JX6qc5FqQPZV33vmGoiPwDpB7btReEiFVt3nyGL7vt6jWuNugN&template_id=C4UE6EaZRYZz2jjHyWaykgvSQVQkMPGbsUYm9DEKq&version=4.1.30.6008&platform=win', '_blank');
            }, 500);
          }
        }
      })

      editor = monaco.editor.create(editorNode, {
        value: '',
        language: 'plaintext',
        theme: 'vs-dark',
        fontFamily: 'Consolas',
        fontWeight: 600,
        fontSize: 14,
        formatOnPaste: true,
        minimap: {
          enabled: true,
        },
      });

      const edits = [
        {
          range: new monaco.Range(0, 0, 0, 0),
          text: '一、已完成：\n',
          forceMoveMarkers: true,
        },
        {
          range: new monaco.Range(1, 0, todayReportLocal.length, 0),
          text: todayReportLocal.map((item: BugReportListItem, i: number) => '   ' + (i + 1) + '. ' + 'Bug ' + item.id + ' ' + item.name + ';' + '\n').join(''),
          forceMoveMarkers: true,
        },
        {
          range: new monaco.Range(1 + todayReportLocal.length, 0, 1 + todayReportLocal.length, 0),
          text: '二、进行中：\n',
          forceMoveMarkers: true,
        },
        {
          range: new monaco.Range(2 + todayReportLocal.length, 0, 2 + todayReportLocal.length, 0),
          text: '三、其它事项：',
          forceMoveMarkers: true,
        },
      ];

      editor!.executeEdits('myEdit', edits);
    });

    createTopBtn('14 天内 bug 历史', async () => {
      bugHistoryModal();
    });

    createTopBtn('收藏列表', () => {
      const collectedBugs = getCollectedBugs();

      if (collectedBugs.length === 0) {
        showMessage(MessageTypeEnum.ERROR, '没有收藏的bug');
        return;
      }

      bugCollectionModal();
    })

    createTopBtn('更新人名映射表', async () => {
      let editor: MonacoEditor = null;
      const { monaco, editorNode } = await createEditorDialog({
        bodyStyle: 'width: 800px; height: 80vh',
        onOk: (closeDialog) => {
          const value = editor!.getValue();

          if (value) {
            localStorage.setItem('personsMap', value);
            closeDialog();
            showMessage(MessageTypeEnum.SUCCESS, '更新成功');
          }
        }
      })

      const personMapStr = localStorage.getItem('personsMap') ?? '{}';

      // @ts-ignore
      editor = monaco.editor.create(editorNode, {
        value: personMapStr,
        language: 'json',
        theme: 'vs-dark',
        fontFamily: 'Consolas',
        fontWeight: 600,
        fontSize: 14,
        formatOnPaste: true,
        hover: {
          enabled: true,
        },
        minimap: {
          enabled: true,
        },
      });
    });
  }
}
